/*
 * casper-daemon.c
 *
 *  Created on: Feb 10, 2011
 *      Author: s126135
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <syslog.h>
#include <string.h>
#include <pthread.h>

#include "list.h"
#include "terminals.h"

#include "daemon.h"
#include "launcher.h"

// PIPES
terminal_t* launcher_daemon_terminal;

int i = 0;

int fork_daemon() {
	pid_t child;
	int res;

	fprintf(stderr, "INFO: main: forking daemon process...\n");
	child = fork();
	if (child < 0) {
		fprintf(stderr, "ERROR: Main: unable to create daemon process\n");
		return EXIT_FAILURE;
	}
	else if (child == 0) {
		// This is the daemon process
		fprintf(stderr, "INFO: Daemon: preparing daemon...\n");
		if (prepare_daemon(launcher_daemon_terminal) == EXIT_FAILURE)
			return EXIT_FAILURE;
		fprintf(stderr, "INFO: daemon: starting daemon_task()...\n");
		exit(daemon_task());
	}
	fprintf(stderr, "INFO: main: daemon fork successful (pid %d)\n", child);
	return EXIT_SUCCESS;
}

int fork_launcher() {
	pid_t child;
	int res;

	fprintf(stderr, "INFO: main: forking launcher process...\n");
	child = fork();
	if (child < 0) {
		fprintf(stderr, "ERROR: Main: unable to create launcher process\n");
		return EXIT_FAILURE;
	}
	else if (child == 0) {
		// This is the launcher process
		fprintf(stderr, "INFO: launcher: preparing launcher...\n");
		if (prepare_launcher(launcher_daemon_terminal) == EXIT_FAILURE)
			return EXIT_FAILURE;
		fprintf(stderr, "INFO: launcher: starting launcher_task()...\n");
		exit(launcher_task());
	}
	fprintf(stderr, "INFO: main: launcher fork successful (pid %d)\n", child);
	return EXIT_SUCCESS;
}

int main (int argc, char *argv[]) {
	char buff[10];

	if (prepare_common() == EXIT_FAILURE)
		return EXIT_FAILURE;

	if (fork_daemon() == EXIT_FAILURE)
		return EXIT_FAILURE;

	if (fork_launcher() == EXIT_FAILURE)
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}

int prepare_common() {
	FILE* stream;

	signal(SIGPIPE, SIG_IGN);

	setenv("CASPER_ROOT_DIR", PREFIX, 1);
	setenv("CASPER_CONF_DIR", SYSCONF, 1);

	// Changing Working Directory
	if (chdir(getenv("CASPER_ROOT_DIR")) < 0) {
		fprintf(stderr, "ERROR: daemon: unable to chdir to %s\n", getenv("CASPER_ROOT_DIR"));
		return EXIT_FAILURE;
	}

	// STDERR redirection
	if ((stream = freopen("log/casper-daemon.log", "w", stderr)) == NULL) {
		fprintf(stderr, "ERROR: unable to open log file\n");
		return EXIT_FAILURE;
	}
	setvbuf(stream,NULL,_IONBF,0);
	// Creating daemon<->launcher terminal
	if ((launcher_daemon_terminal = terminal_new()) == NULL) {
		fprintf(stderr, "ERROR: unable to create daemon<->launcher terminal\n");
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
